<template>
    <el-dialog
      :title="textMap[dialogStatus]"
      v-model="dialogFormVisible"
      width="max-content"
      @closed="onCloseDialog(true)"
    >
       <el-form
        ref="dataForm"
        :rules="rules"
        :model="tempArticleModel"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item
          :label="t('message.layout.type')"
          prop="author"
        >
          <el-input v-model="tempArticleModel.author" placeholder="" />
          <div class=" h-4"></div>
          <el-select
            v-model="tempArticleModel.author"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in calendarTypeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="t('message.layout.date')"
          v-if="tempArticleModel.importance != '经济目标'"
        >
          <el-date-picker
            v-model="selectTime"
            type="datetime"
            placeholder="添加时间"
          />
        </el-form-item>
        <el-form-item
          label="单位"
          prop="abstractContent"
        >
          <el-input v-model="tempArticleModel.abstractContent" />
        </el-form-item>
        <el-form-item
          :label="t('message.layout.title')"
          prop="title"
        >
          <el-input v-model="tempArticleModel.title" />
        </el-form-item>
        <el-form-item :label="t('message.layout.status')" prop="fullContent">
          <el-select
            v-model="tempArticleModel.fullContent"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('message.layout.importance')" prop="status">
          <el-rate
            v-model="tempArticleModel.status"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            :max="3"
            style="margin-top: 8px"
          />
        </el-form-item>
        <el-form-item :label="t('message.layout.remark')" prop="pageviews">
          <el-input
            v-model="tempArticleModel.pageviews"
            :autosize="{minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="输入价值规模"
          />
        </el-form-item>
      </el-form>
      <div class=" h-5"></div>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ t("message.layout.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          {{ t("message.layout.confirm") }}
        </el-button>
         <el-button v-if="isHasDel" type="primary" @click="handleDelete()">
					{{ t('message.layout.delete') }}
				</el-button>
      </div>
    </el-dialog>
</template>

<script lang="ts">
import {
  reactive,
  toRefs,
  defineComponent,
  onDeactivated,
  onActivated,
  onBeforeMount,
  nextTick,
  ref,
  unref,
  computed
} from 'vue';
import { useI18n } from 'vue-i18n';
import { defaultArticleModel } from '/@/request/articles';
import { ElForm, ElMessage } from 'element-plus';
import { cloneDeep } from 'lodash'
export default defineComponent({
  props: {
     modelValue: {
        type: Boolean,
        default: false
    },
    dialogStatus:{
        type:String,
        default:''
    }
  },
  components: {
   
  },
  setup(_, ctx) {
    const dataForm = ref(ElForm);
    const calendarTypeOptions = ['通信类','能源动力','交通枢纽','军工类','生命线','次生灾害','金融类','工矿化工']
    const calendarTypeKeyValue = calendarTypeOptions.reduce(
      (acc: { [key: string]: string }, cur) => {
        acc[cur.key] = cur.displayName
        return acc
      },
      {}
    ) as { [key: string]: string };
     const { t } = useI18n();
    const dataMap = reactive({
      selectTime:new Date(),
      beforeTitle:'',
      isHasDel:false,
      dialogFormVisible:false,
         rowlist:Array<any>({id:Math.random(),
            rowZero: '',
            rowTwo: '',
            rowOne:''
        }),
        importanceOptions: ['市人防办', '市防疫局', '区人防办'],
        statusOptions: ['良好', '破坏', '损毁'],
        calendarTypeOptions: calendarTypeOptions,
        textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        author: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        title: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ],
        status: [
          { required: true, message: 'area is required', trigger: 'blur' }
        ],
      },
        tempArticleModel: defaultArticleModel,
        onAddRow() {
        dataMap.rowlist.push({
          id:Math.random(),
          rowZero: '',
          rowTwo: '',
          rowOne:''
        });
		  },
      resetTempArticleModel() {
        dataMap.tempArticleModel = cloneDeep(defaultArticleModel);
         dataMap.rowlist = [
            {
              id:Math.random(),
              rowZero: '',
              rowTwo: '',
              rowOne:''
            }
          ];
      },
      
      handleCreate(){
        dataMap.isHasDel = false;
        dataMap.dialogFormVisible = true;
         dataMap.resetTempArticleModel();
          nextTick(() => {
          (dataForm.value as typeof ElForm).clearValidate()
        })
      },
      handleUpdate(row: any,isHasDel = false){
        console.log('row = > ',row);
        dataMap.beforeTitle = row.title;
        dataMap.isHasDel = isHasDel;
        dataMap.dialogFormVisible = true;
        dataMap.tempArticleModel = Object.assign({}, row);
        if(dataMap.tempArticleModel.timestamp)
        dataMap.selectTime = new Date(parseInt(dataMap.tempArticleModel.timestamp+""));
        try{
            dataMap.rowlist = [
            {
              id:Math.random(),
              rowZero: '',
              rowTwo: '',
              rowOne:''
            }
          ];
          let arr = JSON.parse(row.fullContent);
          dataMap.rowlist = arr;
        }catch{
        }
         nextTick(() => {
          (dataForm.value as typeof ElForm).clearValidate()
        })
        
      },
      // 删除行
      onDelRow(index){
        dataMap.rowlist.splice(index, 1);
      },
      onCloseDialog(isDrived = false){
        dataMap.dialogFormVisible = false;
        ctx.emit('update:modelValue', false);
        if(isDrived)
        ctx.emit('clearNewDian');
      },
      createData(){
        const form = unref(dataForm)
        form.validate(async(valid: any) => {
          if (valid) {
             dataMap.tempArticleModel.timestamp = dataMap.selectTime.getTime()+"";
            ctx.emit('createData',dataMap.tempArticleModel,dataMap.rowlist);
            dataMap.onCloseDialog();
		      }
        })
        
      },
      updateData(){
        const form = unref(dataForm)
        form.validate(async(valid: any) => {
          if (valid) {
            dataMap.tempArticleModel.timestamp = dataMap.selectTime.getTime()+"";
           ctx.emit('updateData',dataMap.tempArticleModel,dataMap.rowlist);
           dataMap.onCloseDialog();
		      }
        })
      },
      handleDelete(){
        dataMap.tempArticleModel.title= dataMap.beforeTitle;
        ctx.emit('delData',dataMap.tempArticleModel,dataMap.rowlist);
        dataMap.onCloseDialog();
      }
    });
  
      // Because if you enter this page and quickly switch tag, may be in the execution of this.setTagsViewTitle function, this.$route is no longer pointing to the current page
      // https://github.com/PanJiaChen/vue-element-admin/issues/1221
      // tempTagView = Object.assign({}, dataMap.route)
    return {
      ...toRefs(dataMap),t,dataForm
    }
  }
})
</script>